package server.business.ranking;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import server.commonData.SqlStatementEnum;
import server.commonData.Utils;
import server.commonData.interfaces.IUpdate;
import server.jdbc.JDBCException;
import server.msgBean.LoginMessage.RankingListRes;
import server.utils.AbsAsyncQueryDb;

/**
 * 排行榜管理器
 * @author King
 *
 */
public class RankingManager implements IUpdate
{
	private static final int TYPE_MONEY= 1,TYPE_MEILI = 2;
	
	private Map<Integer, List<RankingData>> rankingMap = new HashMap<Integer, List<RankingData>>();
	
	private long nextSortTime;
	
	
	@Override
	public void onTime(long curMill)
	{
		if(curMill<nextSortTime)
			return;
		//2个小时更新一次
		this.nextSortTime = curMill+3600000*2;
		try {
			new QueryRanking(SqlStatementEnum.RANKING_MONEY_QUERTY,TYPE_MONEY);
			new QueryRanking(SqlStatementEnum.RANKING_MEILI_QUERY,TYPE_MEILI);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
		
	
	class QueryRanking extends AbsAsyncQueryDb
	{
		private int type;
		
		public QueryRanking(String sql,int type) throws Exception
		{
			super(sql, new ArrayList());
			this.type = type;
			query(sql, new ArrayList());
			doCallBack();
		}

		@Override
		protected void queryBack()
		{
			List<RankingData> list = new ArrayList<RankingManager.RankingData>();
			for(Map<String, Object> map:this.result)
			{
				RankingData data = new RankingData();
				data.name = Utils.readString(map, "name");
				if(type==TYPE_MONEY)
				{
					data.par = Utils.readInt(map, "money");
				}
				else if(type==TYPE_MEILI)
				{
					data.par = Utils.readInt(map, "meili");
				}
				list.add(data);
			}
			rankingMap.put(this.type, list);
		}
	}
	
	
	public RankingListRes.Builder toClient(int type)
	{
		List<RankingData> list = this.rankingMap.get(type);
		RankingListRes.Builder builder = RankingListRes.newBuilder();
		builder.setType(type);
		for(RankingData data:list)
		{
			builder.addName(data.name);
			builder.addPar(data.par);
		}
		return builder;
	}
	
	
	class RankingData
	{
		String name;
		
		int par;
	}
}
